package com.tous.tool.service;

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

/**
 * @author mengwei
 * @description VideoCompressionService
 * @createDate 2025/7/21 11:45
 */
@Service
public class VideoCompressionService {

    public void compressVideo(File inputFile, File outputFile,
                              int width, int height, int bitrate) throws IOException {

        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
             FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, width, height)) {

            grabber.start();

            // 设置录制器参数
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            recorder.setFormat("mp4");
            recorder.setFrameRate(grabber.getFrameRate());
            recorder.setVideoBitrate(bitrate);
            recorder.setPixelFormat(grabber.getPixelFormat());
            recorder.start();

            Frame frame;
            while ((frame = grabber.grabFrame()) != null) {
                recorder.record(frame);
            }
        }
    }

    public File getCompressedVideoPath(String originalFilename) {
        String compressedDir = "compressed_videos";
        new File(compressedDir).mkdirs();
        return new File(compressedDir, "compressed_" + originalFilename);
    }
}
